<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="page-title">用户管理</h1>
        <div class="breadcrumb-container">
          <router-link to="/" class="link link-hover">首页</router-link>
          <span class="mx-2">/</span>
          <span>用户管理</span>
        </div>
      </div>
      <div class="btn-group">
        <button class="btn btn-primary gap-2" @click="handleNewUser">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
            <path d="M8 9a3 3 0 100-6 3 3 0 000 6zM8 11a6 6 0 016 6H2a6 6 0 016-6zM16 7a1 1 0 10-2 0v1h-1a1 1 0 100 2h1v1a1 1 0 102 0v-1h1a1 1 0 100-2h-1V7z" />
          </svg>
          新增用户
        </button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="card bg-base-100 shadow-lg mb-6">
      <div class="card-body">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">用户名</span>
            </label>
            <input
              v-model="searchForm.username"
              type="text"
              placeholder="请输入用户名"
              class="input input-bordered"
            />
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">角色</span>
            </label>
            <select v-model="searchForm.role" class="select select-bordered">
              <option value="">全部</option>
              <option v-for="role in roles" :key="role.id" :value="role.id">
                {{ role.name }}
              </option>
            </select>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">状态</span>
            </label>
            <select v-model="searchForm.status" class="select select-bordered">
              <option value="">全部</option>
              <option value="active">正常</option>
              <option value="locked">锁定</option>
              <option value="disabled">禁用</option>
            </select>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">创建时间</span>
            </label>
            <div class="join">
              <input
                v-model="searchForm.startTime"
                type="date"
                class="join-item input input-bordered w-[50%]"
              />
              <input
                v-model="searchForm.endTime"
                type="date"
                class="join-item input input-bordered w-[50%]"
              />
            </div>
          </div>
        </div>
        <div class="flex justify-end mt-4">
          <button class="btn btn-ghost" @click="resetSearch">重置</button>
          <button class="btn btn-primary ml-2" @click="handleSearch">搜索</button>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="card bg-base-100 shadow-lg">
      <div class="card-body">
        <div class="overflow-x-auto">
          <table class="table">
            <thead>
              <tr>
                <th>用户名</th>
                <th>角色</th>
                <th>最后登录时间</th>
                <th>最后登录IP</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in users" :key="user.id">
                <td>{{ user.username }}</td>
                <td>
                  <div class="badge badge-ghost" v-for="role in user.roles" :key="role.id">
                    {{ role.name }}
                  </div>
                </td>
                <td>{{ formatDate(user.lastLoginTime) }}</td>
                <td class="font-mono">{{ user.lastLoginIp }}</td>
                <td>
                  <div class="badge" :class="getStatusBadgeClass(user.status)">
                    {{ getStatusLabel(user.status) }}
                  </div>
                </td>
                <td>{{ formatDate(user.createdAt) }}</td>
                <td>
                  <div class="btn-group">
                    <button class="btn btn-ghost btn-sm" @click="handleEdit(user)">
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
                      </svg>
                    </button>
                    <button class="btn btn-ghost btn-sm" @click="handleRoles(user)">
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M9 6a3 3 0 11-6 0 3 3 0 016 0zM17 6a3 3 0 11-6 0 3 3 0 016 0zM12.93 17c.046-.327.07-.66.07-1a6.97 6.97 0 00-1.5-4.33A5 5 0 0119 16v1h-6.07zM6 11a5 5 0 015 5v1H1v-1a5 5 0 015-5z" />
                      </svg>
                    </button>
                    <button class="btn btn-ghost btn-sm" @click="handleStatus(user)">
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z" clip-rule="evenodd" />
                      </svg>
                    </button>
                    <button class="btn btn-ghost btn-sm" @click="handleDelete(user)">
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                      </svg>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="flex justify-between items-center mt-4">
          <div class="text-sm text-base-content/60">
            共 {{ total }} 条记录
          </div>
          <div class="join">
            <button class="join-item btn btn-sm" :disabled="currentPage === 1" @click="handlePageChange(currentPage - 1)">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />
              </svg>
            </button>
            <button class="join-item btn btn-sm">{{ currentPage }} / {{ totalPages }}</button>
            <button class="join-item btn btn-sm" :disabled="currentPage === totalPages" @click="handlePageChange(currentPage + 1)">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <dialog ref="editDialog" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">{{ isEdit ? '编辑用户' : '新增用户' }}</h3>
        <form @submit.prevent="handleSubmit" class="space-y-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">用户名</span>
            </label>
            <input
              type="text"
              v-model="form.username"
              placeholder="请输入用户名"
              class="input input-bordered"
              :class="{ 'input-error': errors.username }"
            />
            <label class="label" v-if="errors.username">
              <span class="label-text-alt text-error">{{ errors.username }}</span>
            </label>
          </div>
          <div class="form-control" v-if="!isEdit">
            <label class="label">
              <span class="label-text">密码</span>
            </label>
            <input
              type="password"
              v-model="form.password"
              placeholder="请输入密码"
              class="input input-bordered"
              :class="{ 'input-error': errors.password }"
            />
            <label class="label" v-if="errors.password">
              <span class="label-text-alt text-error">{{ errors.password }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">状态</span>
            </label>
            <select
              v-model="form.status"
              class="select select-bordered"
              :class="{ 'select-error': errors.status }"
            >
              <option value="active">正常</option>
              <option value="locked">锁定</option>
              <option value="disabled">禁用</option>
            </select>
            <label class="label" v-if="errors.status">
              <span class="label-text-alt text-error">{{ errors.status }}</span>
            </label>
          </div>
        </form>
        <div class="modal-action">
          <button class="btn btn-ghost" @click="closeDialog">取消</button>
          <button
            class="btn btn-primary"
            :class="{ loading: isSubmitting }"
            @click="handleSubmit"
          >
            确定
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>

    <!-- 角色对话框 -->
    <dialog ref="rolesDialog" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">分配角色 - {{ selectedUser?.username }}</h3>
        <div class="space-y-4">
          <div class="form-control" v-for="role in roles" :key="role.id">
            <label class="cursor-pointer label">
              <span class="label-text">{{ role.name }}</span>
              <input
                type="checkbox"
                v-model="selectedRoles"
                :value="role.id"
                class="checkbox"
              />
            </label>
            <p class="text-sm text-base-content/70 ml-2">{{ role.description }}</p>
          </div>
        </div>
        <div class="modal-action">
          <button class="btn btn-ghost" @click="closeRolesDialog">取消</button>
          <button
            class="btn btn-primary"
            :class="{ loading: isUpdatingRoles }"
            @click="handleUpdateRoles"
          >
            确定
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>

    <!-- 删除确认对话框 -->
    <dialog ref="deleteDialog" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg">确认删除</h3>
        <p class="py-4">确定要删除用户"{{ selectedUser?.username }}"吗？此操作不可撤销。</p>
        <div class="modal-action">
          <button class="btn btn-ghost" @click="closeDeleteDialog">取消</button>
          <button
            class="btn btn-error"
            :class="{ loading: isDeleting }"
            @click="confirmDelete"
          >
            删除
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { formatDate } from '@/utils/date'
import { UserService, type User, type Role } from '@/api/services'
import { useLoadingStore } from '@/stores/loading'
import { useToast } from '@/composables/useToast'

const loadingStore = useLoadingStore()
const toast = useToast()

// 状态
const users = ref<User[]>([])
const roles = ref<Role[]>([])
const currentPage = ref(1)
const total = ref(0)
const pageSize = 10

const totalPages = computed(() => Math.ceil(total.value / pageSize))

// 搜索表单
interface SearchForm {
  username: string
  role: string
  status: string
  startTime: string
  endTime: string
}

const searchForm = reactive<SearchForm>({
  username: '',
  role: '',
  status: '',
  startTime: '',
  endTime: '',
})

// 编辑表单
interface Form {
  username: string
  password?: string
  status: string
}

interface FormErrors {
  username?: string
  password?: string
  status?: string
}

const form = reactive<Form>({
  username: '',
  password: '',
  status: 'active',
})

const errors = reactive<FormErrors>({})

// 对话框状态
const editDialog = ref<HTMLDialogElement | null>(null)
const rolesDialog = ref<HTMLDialogElement | null>(null)
const deleteDialog = ref<HTMLDialogElement | null>(null)
const isEdit = ref(false)
const isSubmitting = ref(false)
const isUpdatingRoles = ref(false)
const isDeleting = ref(false)
const selectedUser = ref<User | null>(null)
const selectedRoles = ref<string[]>([])

// 方法
const getStatusBadgeClass = (status: string) => {
  switch (status) {
    case 'active':
      return 'badge-success'
    case 'locked':
      return 'badge-warning'
    case 'disabled':
      return 'badge-error'
    default:
      return 'badge-ghost'
  }
}

const getStatusLabel = (status: string) => {
  switch (status) {
    case 'active':
      return '正常'
    case 'locked':
      return '锁定'
    case 'disabled':
      return '禁用'
    default:
      return '未知'
  }
}

const loadUsers = async () => {
  try {
    loadingStore.show()
    const { items, total: totalCount } = await UserService.getUsers({
      page: currentPage.value,
      pageSize,
      ...searchForm,
    })
    users.value = items
    total.value = totalCount
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    loadingStore.hide()
  }
}

const loadRoles = async () => {
  try {
    loadingStore.show()
    roles.value = await UserService.getRoles()
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    loadingStore.hide()
  }
}

const handleNewUser = () => {
  isEdit.value = false
  form.username = ''
  form.password = ''
  form.status = 'active'
  Object.keys(errors).forEach(key => {
    errors[key as keyof FormErrors] = ''
  })
  editDialog.value?.showModal()
}

const handleEdit = (user: User) => {
  isEdit.value = true
  selectedUser.value = user
  form.username = user.username
  form.status = user.status
  Object.keys(errors).forEach(key => {
    errors[key as keyof FormErrors] = ''
  })
  editDialog.value?.showModal()
}

const handleRoles = async (user: User) => {
  selectedUser.value = user
  selectedRoles.value = user.roles.map(role => role.id)
  if (roles.value.length === 0) {
    await loadRoles()
  }
  rolesDialog.value?.showModal()
}

const handleStatus = (user: User) => {
  selectedUser.value = user
  form.status = user.status
  editDialog.value?.showModal()
}

const handleDelete = (user: User) => {
  selectedUser.value = user
  deleteDialog.value?.showModal()
}

const validateForm = () => {
  let isValid = true
  if (!form.username) {
    errors.username = '请输入用户名'
    isValid = false
  }
  if (!isEdit.value && !form.password) {
    errors.password = '请输入密码'
    isValid = false
  }
  if (!form.status) {
    errors.status = '请选择状态'
    isValid = false
  }
  return isValid
}

const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  try {
    isSubmitting.value = true
    if (isEdit.value && selectedUser.value) {
      const { password, ...updateParams } = form
      await UserService.updateUser(selectedUser.value.id, updateParams)
      toast.success('修改成功')
    } else {
      if (!form.password) {
        errors.password = '请输入密码'
        return
      }
      await UserService.createUser({
        username: form.username,
        password: form.password,
        status: form.status,
      })
      toast.success('新增成功')
    }
    closeDialog()
    loadUsers()
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isSubmitting.value = false
  }
}

const handleUpdateRoles = async () => {
  if (!selectedUser.value) return

  try {
    isUpdatingRoles.value = true
    await UserService.updateUserRoles(selectedUser.value.id, selectedRoles.value)
    toast.success('角色更新成功')
    closeRolesDialog()
    loadUsers()
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isUpdatingRoles.value = false
  }
}

const confirmDelete = async () => {
  if (!selectedUser.value) return

  try {
    isDeleting.value = true
    await UserService.deleteUser(selectedUser.value.id)
    toast.success('删除成功')
    closeDeleteDialog()
    loadUsers()
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isDeleting.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

const resetSearch = () => {
  searchForm.username = ''
  searchForm.role = ''
  searchForm.status = ''
  searchForm.startTime = ''
  searchForm.endTime = ''
  handleSearch()
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  loadUsers()
}

const closeDialog = () => {
  editDialog.value?.close()
}

const closeRolesDialog = () => {
  rolesDialog.value?.close()
}

const closeDeleteDialog = () => {
  deleteDialog.value?.close()
}

// 生命周期
onMounted(() => {
  loadUsers()
  loadRoles()
})
</script>
